package com.wqr.it.ecwdr.service;

import java.util.ArrayList;
import java.util.List;


import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import com.wqr.it.ecwdr.dto.CountryDto;
import com.wqr.it.ecwdr.entity.Country;
import com.wqr.it.ecwdr.repository.CountryRepository;

@Service
@CacheConfig(cacheNames = "country")
public class CountryService {

	@Autowired  
    private CountryRepository countryRepository;
	
	@Cacheable
	public List<CountryDto> findCountryAll() {
		List<CountryDto> clist = new ArrayList<CountryDto> ();
		List<Country> list = countryRepository.findAll();
		if (!CollectionUtils.isEmpty(list)) {
			CountryDto countryDto = null;
			for (Country country : list) {
				countryDto = new CountryDto();
				BeanUtils.copyProperties(country, countryDto);
				clist.add(countryDto);
			}
		}
		return clist;
	}
	
	@Cacheable
	public CountryDto findCountryByCode(String code) {
		Assert.notNull(code);
		Country country = countryRepository.findByCode(code);
		Assert.notNull(country, "Not found country with code " + code);
		CountryDto countryDto = new CountryDto();
		BeanUtils.copyProperties(country, countryDto);
		return countryDto;
	}
	
	@Cacheable
	public CountryDto findCountryById(int id) {
		Assert.notNull(id);
		Country country = countryRepository.findOne(id);
		Assert.notNull(country, "Not found country with id " + id);
		CountryDto countryDto = new CountryDto();
		BeanUtils.copyProperties(country, countryDto);
		return countryDto;
	}


}
